import axios from "axios";
import fileDownload from "js-file-download";

const service = axios.create({
    responseType: 'arraybuffer'
})

service.interceptors.request.use(config => {
    if (window.sessionStorage.getItem('tokenStr')) {
        config.headers['Authorization'] = window.sessionStorage.getItem('tokenStr')
    }
    return config
}, error => {
    console.log(error);
})

service.interceptors.response.use(response => {
    let headers = response.headers
    if (headers['content-type'].match(RegExp('application\/json'))) {
        response.data = arraybuffer2String(response.data)
    } else {
        let fileName = decodeURIComponent(headers['content-disposition'].split(';')[1].split('filename=')[1]);
        let contentType = headers['content-type']
        fileDownload(response.data, fileName, contentType)
    }
}, error => {
    console.log(error);
})

function arraybuffer2String(arraybuffer) {

    // let arrayStr = String.fromCharCode.apply(null, new Uint8Array(arraybuffer));
    // let decodedString = decodeURIComponent(escape(arrayStr))
    // console.log(decodedString);
    // return JSON.parse(decodedString)

    // 另一种方式
    var enc = new TextDecoder("utf-8");
    return enc.decode(new Uint8Array(arraybuffer))
}

let base = ''

export const downloadRequest = (url) => {
    return service.get(`${base}${url}`)
}